<template>
    <div class="login-page" @contextmenu="handleContextMenu">
      <div class="login-wrap">
          <el-form ref="form" :model="form">
            <h1 class="title">工一云电脑</h1>
            <el-form-item >
              <el-input :class="[isMobile ? 'el-input-login-mobile' : 'el-input-login']" type="text" v-model="form.username"  placeholder="用户账号" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item >
              <el-input :class="[isMobile ? 'el-input-login-mobile' : 'el-input-login']" type="password" v-model="form.password" placeholder="用户密码" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button :class="[isMobile ? 'el-input-login-mobile' : 'el-input-login']" type="primary" @click="doLogin" style="width: 100%;">登陆</el-button>
            </el-form-item>
            <!-- <el-form-item v-if="isMobile"> -->
            <el-form-item>
              <!-- <div>-->
              <!-- <el-row  style="text-align: center;margin-top: -10px; color: white; margin: auto;display: flex;justify-content: space-between;" :class="[isMobile ? 'el-input-login-mobile' : 'el-input-login']"> -->
              <el-row  style="text-align: center;margin-top: -10px; color: white; margin: auto;display: flex;justify-content: space-around;" class="el-input-login-mobile">  
                  <span><el-link type="primary" @click="doGateway" style="color: white;" >设置网关</el-link></span>
                  <span><el-link type="primary" @click="doRegister" style="color: white;">修改密码</el-link></span>
              </el-row>
              <!--</div> -->
            </el-form-item>
          </el-form>
      </div>
      <el-dialog
            :custom-class="[isMobile ? 'el-dialog-input-login-mobile' : 'el-dialog-input-login', 'rdp-dialog']"
            title="工一云电脑管理后台地址设置"
            :visible.sync="Successdialog" 
            :show-close= false 
            :close-on-click-modal= true 
            :close-on-press-escape= false
            :modal="false" 
            width="40%"
            center>
            <el-form ref="form" :model="form">
            <el-form-item >
              <el-input type="text" v-model="form.manager_server"  placeholder="管理后台地址" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="Successdialog = false">取消</el-button>
            <el-button type="primary" @click="confirmView">确认</el-button>
          </span>
      </el-dialog>

      <el-dialog
            :custom-class="[isMobile ? 'el-dialog-input-login-mobile' : 'el-dialog-input-login', 'rdp-dialog']"
            title="工一云电脑用户密码修改"
            :visible.sync="changePw" 
            :show-close= false 
            :close-on-click-modal= true 
            :close-on-press-escape= false
            :modal="false" 
            width="60%"
            center>
            <el-form ref="form" :model="form">
              <el-form-item >
                <el-input type="text" v-model="form.username"  placeholder="用户名" autocomplete="off"></el-input>
              </el-form-item>  
              <el-form-item >  
                <el-input type="text" v-model="form.code"  @change="handleInputCodeComplete" placeholder="验证码" autocomplete="off" style="width: 60%;"></el-input><el-button style="margin-left: 2%;width: 38%;" @click="smssend">短信验证码</el-button>
              </el-form-item>
              <el-form-item >
                <el-input type="password" v-model="form.newpw"  placeholder="新密码" autocomplete="off"></el-input>
              </el-form-item>
                <el-form-item >
                <el-input type="password" v-model="form.newpw2"  @change="handleInputnewpw2Complete"  placeholder="新密码确认" autocomplete="off"></el-input>
              </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="changePw = false">取消</el-button>
            <el-button type="primary" @click="changePwConfirm">确认</el-button>
          </span>
      </el-dialog>

      <el-dialog
            :custom-class="[isMobile ? 'el-dialog-input-login-mobile' : 'el-dialog-input-login', 'rdp-dialog']"
            title="工一云电脑选择界面"
            :visible.sync="SuccessSelect" 
            :show-close= false 
            :close-on-click-modal= true 
            :close-on-press-escape= false
            :modal="true" 
            width="40%"
            center>
            <el-form ref="form" :model="form">
            <el-form-item  v-for="(item, index) in ccNames" :key="index" >
              <!-- <el-input type="text" v-model="form.manager_server"  placeholder="管理后台地址" autocomplete="off"></el-input> -->
                <!-- <span v-text="item"></span> -->
                <el-image :id="item" :name="index" style="width: 100%;" :src="require('@/assets/cc1.png')" :fit="fit"  @click="selectfun"/>
                <span v-text="item" style="position: absolute;top: 20%;left: 48%;color: white;"></span>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="SuccessSelect = false">取消</el-button>
            <!-- <el-button type="primary" @click="confirmView">确认</el-button> -->
          </span>
      </el-dialog>
  </div>
  </template>
  <script>
    import axios from 'axios'
    export default{
     
       data(){
         return{
           form:{
             username:'',
             password:'',
             manager_server: "",
             code: "",
             newpw: "",
             newpw2: "",
           },
           Successdialog: true,//控制弹出
           Sencond: "认证成功",//设置初始倒计时
           isMobile: false,
           isTouch: false,
           SuccessSelect: false,//控制弹出选择界面
           ccList: [],
           ccNames: [],
           ccIds: [],
           ImageUrl: "cc1.png",
           changePw: false,
           code: "",
           codecheck: false,
           newpwcheck: false,
         }
       },
   
      created(){
          window.addEventListener('resize', this.checkMobile);
          this.checkMobile(); //初始化时进行判断是否是移动设备 
          localStorage.setItem("managerserver", "http://cem.cec.cc:8069"); //设置默认服务器参数
          this.checkMobileManagerSserver();  //初始化时进行判断是否存在了服务器参数
      },

      mounted() {
        window.addEventListener('keydown', this.handleKeyDown);
        this.checkTouch();
        let cc_vmid = this.$route.query.vmid
        let user_uuid = this.$route.query.user_uuid
        let vnc_address = this.$route.query.vnc_address
        let username = this.$route.query.username
        let password = this.$route.query.password
        let cecip= this.$route.query.cecip
        let cecusername = this.$route.query.cecusername
        let vmid = this.$route.query.cc_vmid
        console.log(cecip)
        console.log(cecusername)
        if(cc_vmid != undefined && user_uuid != undefined && vnc_address == undefined){
          sessionStorage.setItem('user_uuid', user_uuid);
          sessionStorage.setItem('manager_server', this.form.manager_server);
          sessionStorage.setItem('cc_vmid', cc_vmid);
          // 新添加测试vnc
          //sessionStorage.setItem('asset_protocol', "vnc");
          // 
          //this.$router.push('/Main');
        }
        else if(cc_vmid != undefined && user_uuid != undefined && vnc_address != undefined){
          sessionStorage.setItem('user_uuid', user_uuid);
          sessionStorage.setItem('manager_server', this.form.manager_server);
          sessionStorage.setItem('cc_vmid', cc_vmid);
          // 新添加测试vnc
          sessionStorage.setItem('asset_protocol', "vnc");
          sessionStorage.setItem('asset_host', vnc_address);
          // 
          this.$router.push('/Main');
        }
        else if(cecip != undefined && cecusername != undefined){
          sessionStorage.setItem('cecip', cecip);
          sessionStorage.setItem('user_uuid', cecusername);
          this.$router.push('/UpLoad');
        }
        else if(username != undefined && password != undefined && vmid != undefined){
          console.log(vmid)
          sessionStorage.setItem('cc_vmid', vmid);
          this.$router.push('/Main');
        }
        else if(username != undefined && password != undefined){
          this.form.username = username
          this.form.password = password
          this.doLogin()
        }else{
          this.$router.push('/Main');
        }
      },

      beforeUnmount() {
        window.removeEventListener('keydown', this.handleKeyDown);
      },

      destroyed() {
        window.removeEventListener('resize', this.checkMobile);
      },

       methods:{
        doGateway(){
          this.Successdialog = true;
        },

        checkTouch() {
        //this.isMobile = window.innerWidth <= 767;
        //console.log(this.isMobile) 
        if('ontouchstart' in window || navigator.maxTouchPoints){
          this.isTouch = true;
        }
        else{
          this.isTouch = false;
        }
        console.log("isTouch", this.isTouch);
        
        //return this.isMobile;
      },

        objToParams(obj) {
        let arr = [];
        for (let key in obj) {
            arr.push(`${key}=${obj[key]}`);
        }
            return arr.join('&');
        },
        
        doLogin(){
          this.handlefullscreen()
          sessionStorage.setItem('username', this.form.username)
          //console.log(this.objToParams(this.form))
          // this.$message({
          //        message: '登陆成功',
          //        type: 'success'
          //      });
          //this.form.manager_server = "https://erptest.cec.cc"
          axios({
                url: "/api/login",
                method: "post",
                headers: {
                    'Content-Type':'application/x-www-form-urlencoded',
                },
                data: this.objToParams(this.form)
            }).then(response => {
                    if(response.data.status){
                      //   this.$message({
                      //   message: '登陆成功',
                      //   type: 'success'
                      // });
                      // console.log(response.data.Data)
                      sessionStorage.setItem('user_uuid', response.data.Data.user_uuid);
                      sessionStorage.setItem('manager_server', this.form.manager_server);
                      sessionStorage.setItem('password', this.form.password);
                      // this.$router.push('/Main');
                              axios({
                                  url: "/api/getuser2vmrdpinfo",
                                  method: "post",
                                  headers: {
                                      'Content-Type':'application/x-www-form-urlencoded',
                                  },
                                  data: this.objToParams({'username':this.form.username, 'manager_server':this.form.manager_server})
                              }).then(response => {
                                        //console.log(response)
                                        //console.log(response.data.status)
                                        // console.log(response.data)
                                        if(response.data.length > 0){
                                          //   this.$message({
                                          //   message: '登陆成功',
                                          //   type: 'success'
                                          // });
                                        //   sessionStorage.setItem('user_uuid', response.data.Data.user_uuid);
                                        //   sessionStorage.setItem('manager_server', this.form.manager_server);
                                          // this.$router.push('/Main');
                                        this.ccList = response.data.ipv4
                                        this.ccNames = response.data.data
                                        this.SuccessSelect = true
                                        sessionStorage.setItem('ccList', this.ccList);
                                        console.log(response.data);
                                        this.ccIds = response.data.ids
                                      }
                                      else{
                                        this.$message({
                                          message: '登录失败',
                                          type: 'fail'
                                        });
                                      }
                                  }
                              ).catch(error => {
                                      console.log(456)
                                      console.log(error)
                                  }
                              );  

                      // 
                    }
                    else{
                      this.$message({
                        message: '登录失败',
                        type: 'fail'
                      });
                    }
                }
            ).catch(error => {
                    console.log(456)
                    console.log(error)
                }
            );
        //this.$router.push('/Main');
         },
         doRegister(){
           //this.$router.push('/register');
           this.changePw = true;
         },

         checkMobile() {
          this.isMobile = window.innerWidth <= 767;
          console.log(this.isMobile)    
          },
          
          checkMobileManagerSserver() {
            try{
              this.form.manager_server = localStorage.getItem("managerserver");
              console.log(this.form.manager_server)
              console.log("try")
            }
            catch{
              this.form.manager_server =""
              console.log("catch")
            }
            console.log(this.form.manager_server);
            if (this.form.manager_server != null){
              this.Successdialog = false;
            }
          },

          confirmView(){
            console.log(this.form.manager_server);
            localStorage.setItem("managerserver", this.form.manager_server);
            this.Successdialog = false;
          },

          handleKeyDown(event) {
              if (event.key === 'Enter') {
                // 处理回车键按下事件
                console.log("回车键按下事件")
                this.doLogin()
              }
              if (event.ctrlKey && event.altKey && event.key === 'c'){
                // 处理alt+ctrl+c按下事件
                console.log("处理alt+ctrl+c按下事件")
                this.Successdialog = true
              }
        },

        selectfun(ev){
          console.log(ev)
          console.log(ev.target.id)
          console.log(ev.target.name)
          this.SuccessSelect = false
          // sessionStorage.setItem('cc_vmid', ev.target.id);
          sessionStorage.setItem('cc_vmid', this.ccList[parseInt(ev.target.name)]);
          sessionStorage.setItem('index', this.ccIds[parseInt(ev.target.name)] );
          this.$router.push('/Main');
        },

        // 右键拦截
        handleContextMenu(event) {
          event.preventDefault(); // 取消默认的上下文菜单行为
    
        // 这里可以编写自定义的右键菜单逻辑
        console.log("右键点击");
        },

        smssend(){
          if(this.form.username == ""){
            this.$message({
              message: '请填入用户名称',
              type: 'fail'
            });
            return
          }
          this.code = Math.floor(Math.random() * 9000) + 1000;
          axios({
                url: "/api/smssend",
                method: "post",
                headers: {
                    'Content-Type':'application/x-www-form-urlencoded',
                },
                
                data: this.objToParams({'username':this.form.username, 'manager_server':this.form.manager_server, "code": this.code})
            }).then(response => {
                      console.log(response.data)
                      if(response.data == "发送成功"){
                        this.$message({
                          message: '短信验证码发送成功',
                          type: 'success'
                        });
                      }
                      else{
                        this.$message({
                          message: '短信验证码发送失败',
                          type: 'fail'
                        });
                      }
                }
            ).catch(error => {
                    console.log(456)
                    console.log(error)
                    this.$message({
                      message: '短信验证码发送失败',
                      type: 'fail'
                    });
                }
            );  
        },

        handleInputCodeComplete(){
          if(this.code == this.form.code){
            this.$message({
              message: '验证码验证成功',
              type: 'success'
            });
            this.codecheck = true;
          }else{
            this.$message({
              message: '验证码验证失败',
              type: 'fail'
            });
            this.codecheck = false;
          }
        },

        handleInputnewpw2Complete(){
          if(this.form.newpw == this.form.newpw2){
            // this.$message({
            //   message: '新密码验证成功',
            //   type: 'success'
            // });
            this.newpwcheck = true;
          }else{
            this.$message({
              message: '新密码验证失败',
              type: 'fail'
            });
            this.newpwcheck = false;
          }
        },

        changePwConfirm(){
          if(!this.codecheck){
            this.$message({
              message: '验证码验证失败',
              type: 'fail'
            });
          }else if(!this.newpwcheck){
            this.$message({
              message: '新密码验证失败',
              type: 'fail'
            });
          }
          else{
            console.log("准备修改密码")
            axios({
                url: "/api/smschangepw",
                method: "post",
                headers: {
                    'Content-Type':'application/x-www-form-urlencoded',
                },
                
                data: this.objToParams({'username':this.form.username, 'manager_server':this.form.manager_server, "newpassword": this.form.newpw2})
            }).then(response => {
                      console.log(response.data)
                      if(response.data == "密码修改成功"){
                        this.$message({
                          message: '密码修改成功',
                          type: 'success'
                        });
                        this.changePw = false;
                      }
                      else{
                        this.$message({
                          message: '修改失败，建议密码长度为8位以上,数字加字母加符号组合',
                          type: 'fail'
                        });
                      }
                }
            ).catch(error => {
                    console.log(456)
                    console.log(error)
                    this.$message({
                      message: '修改密码失败',
                      type: 'fail'
                    });
                }
            );  
          }
        },

        handlefullscreen(){
          if (!document.fullscreenElement) {
            this.enterFullScreen();
          } 
        },

        enterFullScreen() {
          let element = document.documentElement;
          if (element.requestFullscreen) {
            element.requestFullscreen();
          } else if (element.mozRequestFullScreen) { /* Firefox */
            element.mozRequestFullScreen();
          } else if (element.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
            element.webkitRequestFullscreen();
          } else if (element.msRequestFullscreen) { /* IE/Edge */
            element.msRequestFullscreen();
          }
        },

       }
   
   
   
    }
  </script>
   
  <style>
        .el-link-gy{
          color: white !important;
        }

        .login-page{
          background-color: rgb(38,92,178);
          height: 100vh;
          width: 100vw;
          background-image:  url('~@/assets/2.png');
          background-size: cover;
          /* background-size: 100%; */
          margin: -8px;
        }

        .login-wrap {
            box-sizing: border-box;
            width: 100%;
            height: 100%;
            padding-top: 10%;
           
            
            background-repeat: no-repeat;
            background-position: center right;
            background-size: 100%;
        }
   
        .login-container {
            border-radius: 10px;
            margin: 0px auto;
            width: 350px;
            padding: 30px 35px 15px 35px;
            background: #fff;
            border: 1px solid #eaeaea;
            text-align: left;
            box-shadow: 0 0 20px 2px rgba(0, 0, 0, 0.1);
        }
   
        .title {
            width: 50%;
            margin: 0px auto 40px auto;
            text-align: center;
            color: white;
        }
        /* .el-input{ */
          /* width: 20% !important; */
        /* } */
        .el-button--primary{
          width: 20% !important;
        }
        .block {
        text-align: center;
        .picker-box {
          width: 100%;
          ::v-deep .el-input__inner {
            border: none;
            border-radius: 0;
            padding-bottom: 1px;
            border-bottom: 1px solid #ccc;
              }
            }
        }
        .el-input-login{
          width: 30%  !important;
        }

        .el-input-login-mobile{
          width: 80%  !important;
        }

        .el-dialog-input-login{
          width: 30%  !important;
        }

        .el-dialog-input-login-mobile{
          width: 90%  !important;
        }

        /* .el-form-item::after{
          height: 50vh;
          width: 50vw;
          background-image:  url('~@/assets/cc1.png');
          background-size: cover;
        } */
  </style>